__author__ = 'vincent LIU'

from NetValueLoader import *
import TradingDates
import os
import chksignal

def WriteNetValueBookHeader(output_path,date):
	fd = open(output_path + "\\" + "netValueBook." + date + ".csv","w+")
	fd.write("#product,\
	netValue,\
	netValuePerShr,\
	fundShare,\
	totalStockValue,\
	accumulatedIntEarned,\
	totalStockDividend,\
	totalTradedAmount,\
	totalStockComm,\
	accumulatedDeposit,\
	stockAccountCash,\
	stockAccountAssets,\
	previousFutureEquity,\
	currentFuturePnl,\
	currentFutureComm,\
	currentFutureDeposit,\
	futureEquity,\
	accumulatedIntCharged,\
	totalValue,\
	currentStockPnlExcludeETF,\
	currentStockMvExcludeETF\n"
	         )
	return fd

def GetCurStkPnl(pnl,date,prod,nv_path):
	ldate = TradingDates.GetLastDate(date)
	last_nv = nvValue(ldate,prod,nv_path)
	last_nv.Load_StockInfo()
	return pnl - last_nv.stk_pnl

def runNetValueBook(sdate,edate,prodlist,disk,output_path):
	prodlist = prodlist.split(',')
	if TradingDates.IsTradingDate(sdate):
		pass
	else:
		sdate = TradingDates.GetNextDate(sdate)
	cdate = sdate
	while True:
		fd = WriteNetValueBookHeader(output_path,cdate)
		for prod in prodlist:
			if  prod != '3':
				if chksignal.begin_chk(cdate,prod) == 0:
					pass
			nv_path = disk + ":\\data\\WindDB\\production"+prod+"\\netValue\\"
			fname  =nv_path +cdate + ".prod" + prod + ".xlsx"
			if not os.path.exists(fname):
				continue
			nv = nvValue(cdate,prod,nv_path)
			nv.Load_CurStockDetail()
			nv.Load_FundTable()
			nv.Load_FutureInfo()
			nv.Load_StockInfo()
			stk_pnl = GetCurStkPnl(nv.stk_pnl,nv.date,prod,nv_path)
			nv.WriteNetValueTable(fd,prod,stk_pnl)
		cdate = TradingDates.GetNextDate(cdate)
		fd.close()
		if cdate > edate:
			break
		else:
			continue